# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
  
  LANGUAGE_NAMES = Hash.new
  # load the native language names into the constant
  SUPPORTED_LANGUAGES.each do |lang, locale|
    LANGUAGE_NAMES.merge!({locale => (langobj = Language.pick(locale)).nil? ? lang.to_s : langobj.native_name })
  end
  
  
  # Check for user authorization
  def is_admin?
    logged_in? && current_user.is_admin
  end
  
  def is_approved?
    logged_in? && current_user.is_approved
  end
  
  # Create a nicer language menu than the Click-To-Globalize default
  def languages_menu
    result = "<form action=" + url_for(:action => 'set', :controller => 'locale') + ">\n" 
    result << "<select name='id' onchange='this.form.submit()'>\n"
    # We'll sort the languages by their keyname rather than have all the non-arabic-character-set
    # ones end up at the end of the list.
    LANGUAGE_NAMES.sort {|a, b| a.first.to_s <=> b.first.to_s }.each do |locale, langname|
      langname = langname.titleize;     
      if locale.casecmp(Locale.active.code) == 0
        result << "<option value=#{locale} selected><strong>#{langname}</strong></option>\n"
      else
        result << "<option value=#{locale}>#{langname}</option>\n"
      end
    end
    result << "</select>"
    result << "<noscript><input type=submit name=commit value='Go'></noscript>"
    result << "</form>"
    return result
  end  
  
  def translate_safely(*chunks)
    result = ""    
    chunks.each do |str, link, linkopts| 
      if link.blank?
        result << "<span>" + h(str.t) + "</span>\n"
      else
        result << link_to( h(str.t), link, linkopts) + "\n"
      end
    end
    return result
  end
  
end
